<template>
  <div id="write">
    <Form ref="Article" :model="Article" :rules="rule">
      <br />
      <br />
      <br />
      <br />
      <Row>
        <Col span="20" offset="2">
          <FormItem prop="title">
            <Input type="text" v-model="Article.title" placeholder="请输入标题"></Input>
          </FormItem>
        </Col>
      </Row>
      <Row id="ckeditor">
        <Col span="20" offset="2">
          <FormItem prop="content">
            <ckeditor
              :editor="editor"
              v-model="Article.content"
              :config="editorConfig"
              @input="save"
            ></ckeditor>
          </FormItem>
        </Col>
      </Row>
      <Row>
        <Col span="20" offset="2">您的所有更改会自动保存到本地，退出当前账户将自动清空。</Col>
      </Row>
      <Row>
        <FormItem>
          <Button type="primary" size="large" :loading="loading" @click="onSubmit">提交</Button>
        </FormItem>
      </Row>
    </Form>
    <Row></Row>
  </div>
</template>

<script>
import ClassicEditor from "@ckeditor/ckeditor5-build-classic";
import '@ckeditor/ckeditor5-build-classic/build/translations/zh-cn';
export default {
  name: "write",
  data() {
    return {
      editor: ClassicEditor,
      editorConfig: {
        language: "zh-cn",
        ckfinder: {
　　　　　　uploadUrl: `api/ckeditor/upload/`,
　　　　　},
      },
      loading:false,
      Article: {
        title: "",
        content: "",
      },
      rule: {
        content: [
          { required: true, message: "请输入内容", trigger: "change,blur" },
        ],
        title: [
          { required: true, message: "请输入题目", trigger: "change,blur" },
        ],
      },
    };
  },
  created: function () {
    this.Article.content = localStorage.getItem("ckeditor_content");
  },
  methods: {
    save() {
      localStorage.setItem("ckeditor_content", this.Article.content);
    },
    onSubmit() {
      this.$refs["Article"].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$api.post(
            "articles/",
            {
              title: this.Article.title,
              content: this.Article.content,
            },
            (response) => {
              this.loading = false;
              if (response.status != 200) {
                this.$Message.error("提交失败，服务器错误");
                this.$Message.error("" + response);
              } else {
                var data = response.data;
                if (data.err_code == 0) {
                  this.$Message.success("提交成功");
                  localStorage.removeItem("ckeditor_content");
                  this.$router.push({
                    path: `/view/${data.data.id}`,
                  });
                } else {
                  this.$Message.error("提交失败");
                  this.$Message.error(data.error);
                }
              }
            }
          );
        } else {
          this.loading = false;
        }
      });
    },
  },
};
</script>
<style scoped>
</style>